/**
 * 保存所编辑的文件
 * // -- TODO 连接mongoDB, 保存到mongoDB数据库中
 * Created by mlr on 2017/3/10.
 */
var path = require('path'),
    fs  = require('fs'),
    config = require('config'),
    util = require(path.join(APP_BASE.S, 'util'));

exports = module.exports = function(req, res) {
    var _data = req.body || req.query;
    var data = JSON.parse(_data.data);
    var md_content = data.md, fileName = data.fileName,
        fileId = data.fileId, md_html_content = data.html;
    var md_folder = config.get('MD_FILE_FOLDER');
    var md_html_folder = config.get('MD_HTML_FILE_FOLDER');
    var flag = !fileId;
    if (flag) {
        var procSave = util.appendData({fileName: fileName});
        if (procSave.err != 0) {
            return res.send(procSave);
        }
        fileId = procSave._id;
    } else {
        var saveResult = util.modifyData({
            _id: fileId, fileName: fileName
        });
        if (saveResult.err != 0) {
            res.send(saveResult);
            return;
        }
    }
    var md_path = md_folder + fileId + '.md';
    var md_html_path = md_html_folder + fileId + '.html';
    fs.writeFileSync(md_path, md_content);
    fs.writeFileSync(md_html_path, md_html_content);
    res.send({ err: 0, data: { fileId: fileId } });
};


